package cn.dengta.webapp.ai.model;

import java.util.*;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.annotation.JSONField;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class AIGCMessages {

	private List<AIGCMessage> messages;

	private AIGCMessages() {
	}

	public AIGCMessages addMessage(@NotNull AIGCMessage message) {
		getMessages().add(message);
		return this;
	}

	public AIGCMessages addMessages(@NotNull AIGCMessages messages) {
		getMessages().addAll(messages.getMessages());
		return this;
	}

	/**
	 * 添加一条 AI 消息
	 *
	 * @param sendName 可空，如果为空使用 ai 昵称，非空时强制使用传入称呼
	 * @param content 消息内容
	 * @param createdSec 时间戳，秒
	 */
	public AIGCMessages addAiMessage(@NotNull String content, @NotNull Long createdSec) {
		getMessages().add(AIGCMessage.fromAi(content, createdSec));
		return this;
	}

	/**
	 * 添加一条 用户 消息
	 *
	 * @param content 消息内容
	 * @param createdSec 时间戳，秒
	 */
	public AIGCMessages addUserMessage(@NotNull String content, @NotNull Long createdSec) {
		getMessages().add(AIGCMessage.fromUser(content, createdSec));
		return this;
	}

	public static AIGCMessages of() {
		return new AIGCMessages();
	}

	public boolean nonMsg() {
		return getMessages().isEmpty();
	}

	public List<AIGCMessage> getMessages() {
		if (messages == null) {
			messages = new ArrayList<>();
		}
		return messages;
	}

	public static AIGCMessages from(@NotEmpty String json) {
		AIGCMessages aigcMessages = JSON.parseObject(json, AIGCMessages.class);
		aigcMessages.validate();
		return aigcMessages;
	}

	public void validate() {
		for (AIGCMessage message : messages) {
			message.validate();
		}
	}

	public static AIGCMessages fromSample(@NotEmpty String json) {
		AIGCMessages aigcMessages = JSON.parseObject(json, AIGCMessages.class);
		for (AIGCMessage message : aigcMessages.messages) {
			message.validateSample();
		}
		return aigcMessages;
	}

	@JSONField(serialize = false)
	public AIGCMessage getLast() {
		if (nonMsg()) {
			return null;
		}
		return getMessages().get(getMessages().size() - 1);
	}

	public void sort() {
		getMessages().sort(Comparator.comparing(AIGCMessage::getCreated));
	}

}
